<template>
  <div class="project-settings-container">
    <n-card class="settings-card">
      <template #header>
        <div class="card-header">
          <h1>项目设置</h1>
          <div class="header-actions">
            <n-button @click="goBack">
              <template #icon><n-icon><ArrowBackOutline /></n-icon></template>
              返回
            </n-button>
            <n-button type="primary" @click="saveSettings">
              <template #icon><n-icon><SaveOutline /></n-icon></template>
              保存
            </n-button>
          </div>
        </div>
      </template>
      
      <n-tabs type="line" animated>
        <n-tab-pane name="basic" tab="基本设置">
          <n-form
            ref="formRef"
            :model="projectForm"
            :rules="formRules"
            label-placement="left"
            label-width="120"
            require-mark-placement="right-hanging"
          >
            <n-form-item label="项目名称" path="name">
              <n-input v-model:value="projectForm.name" placeholder="请输入项目名称" />
            </n-form-item>
            
            <n-form-item label="项目描述" path="description">
              <n-input
                v-model:value="projectForm.description"
                type="textarea"
                placeholder="请输入项目描述"
                :autosize="{ minRows: 3, maxRows: 5 }"
              />
            </n-form-item>
            
            <n-form-item label="标签" path="tags">
              <n-dynamic-tags v-model:value="projectForm.tags" />
            </n-form-item>
            
            <n-form-item label="可见性" path="visibility">
              <n-select
                v-model:value="projectForm.visibility"
                :options="visibilityOptions"
                placeholder="请选择可见性"
              />
            </n-form-item>
            
            <n-form-item label="缩略图" path="thumbnail">
              <n-upload
                action="#"
                :default-upload="false"
                :on-before-upload="beforeUploadThumbnail"
                accept="image/*"
                list-type="image-card"
                :max="1"
              >
                <div v-if="!projectForm.thumbnail">
                  <n-icon size="20">
                    <ImageOutline />
                  </n-icon>
                  <div>点击上传</div>
                </div>
                <img
                  v-else
                  :src="projectForm.thumbnail"
                  alt="缩略图"
                  style="max-width: 100%; max-height: 100%"
                />
              </n-upload>
            </n-form-item>
          </n-form>
        </n-tab-pane>
        
        <n-tab-pane name="resolution" tab="分辨率与帧率">
          <n-form
            label-placement="left"
            label-width="120"
          >
            <n-form-item label="分辨率" path="resolution">
              <n-select
                v-model:value="selectedResolution"
                :options="resolutionOptions"
                placeholder="请选择分辨率"
              />
            </n-form-item>
            
            <n-form-item label="自定义分辨率" v-if="selectedResolution === 'custom'">
              <n-input-group>
                <n-input-number
                  v-model:value="projectForm.resolution.width"
                  placeholder="宽度"
                  :min="100"
                  :max="7680"
                />
                <n-text style="padding: 0 8px;">x</n-text>
                <n-input-number
                  v-model:value="projectForm.resolution.height"
                  placeholder="高度"
                  :min="100"
                  :max="4320"
                />
              </n-input-group>
            </n-form-item>
            
            <n-form-item label="帧率" path="frameRate">
              <n-select
                v-model:value="projectForm.frameRate"
                :options="frameRateOptions"
                placeholder="请选择帧率"
              />
            </n-form-item>
          </n-form>
        </n-tab-pane>
        
        <n-tab-pane name="advanced" tab="高级设置">
          <n-form
            label-placement="left"
            label-width="120"
          >
            <n-form-item label="自动保存">
              <n-switch v-model:value="projectForm.autoSave" />
            </n-form-item>
            
            <n-form-item label="自动保存间隔" v-if="projectForm.autoSave">
              <n-input-number
                v-model:value="projectForm.autoSaveInterval"
                :min="1"
                :max="30"
                :step="1"
                suffix="分钟"
              />
            </n-form-item>
            
            <n-form-item label="版本控制">
              <n-switch v-model:value="projectForm.versionControl" />
            </n-form-item>
            
            <n-form-item label="物理引擎">
              <n-switch v-model:value="projectForm.physicsEnabled" />
            </n-form-item>
            
            <n-divider />
            
            <n-form-item label="导出设置">
              <n-space vertical>
                <n-checkbox v-model:checked="projectForm.exportSettings.includeAudio">
                  包含音频
                </n-checkbox>
                <n-checkbox v-model:checked="projectForm.exportSettings.includeMetadata">
                  包含元数据
                </n-checkbox>
                <n-checkbox v-model:checked="projectForm.exportSettings.optimizeForWeb">
                  优化 Web 播放
                </n-checkbox>
              </n-space>
            </n-form-item>
            
            <n-form-item label="默认导出格式">
              <n-select
                v-model:value="projectForm.exportSettings.defaultFormat"
                :options="exportFormatOptions"
                placeholder="请选择导出格式"
              />
            </n-form-item>
          </n-form>
        </n-tab-pane>
        
        <n-tab-pane name="collaborators" tab="协作者">
          <div class="collaborators-section">
            <div class="section-header">
              <h3>项目协作者</h3>
              <n-button size="small" @click="showAddCollaboratorModal = true">
                <template #icon><n-icon><PersonAddOutline /></n-icon></template>
                添加协作者
              </n-button>
            </div>
            
            <n-data-table
              :columns="collaboratorColumns"
              :data="projectForm.collaborators || []"
              :bordered="false"
              :single-line="false"
              :pagination="{ pageSize: 10 }"
              v-if="projectForm.collaborators && projectForm.collaborators.length > 0"
            />
            
            <n-empty
              v-else
              description="暂无协作者"
            >
              <template #extra>
                <n-button @click="showAddCollaboratorModal = true">添加协作者</n-button>
              </template>
            </n-empty>
          </div>
        </n-tab-pane>
      </n-tabs>
    </n-card>
    
    <!-- 添加协作者对话框 -->
    <n-modal
      v-model:show="showAddCollaboratorModal"
      title="添加协作者"
      preset="dialog"
      positive-text="添加"
      negative-text="取消"
      @positive-click="addCollaborator"
      @negative-click="cancelAddCollaborator"
    >
      <n-form
        ref="collaboratorFormRef"
        :model="collaboratorForm"
        :rules="collaboratorRules"
        label-placement="left"
        label-width="80"
      >
        <n-form-item label="用户名" path="username">
          <n-input v-model:value="collaboratorForm.username" placeholder="请输入用户名或邮箱" />
        </n-form-item>
        
        <n-form-item label="角色" path="role">
          <n-select
            v-model:value="collaboratorForm.role"
            :options="roleOptions"
            placeholder="请选择角色"
          />
        </n-form-item>
      </n-form>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import {
  NCard,
  NButton,
  NIcon,
  NTabs,
  NTabPane,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NInputGroup,
  NSelect,
  NSwitch,
  NUpload,
  NEmpty,
  NDynamicTags,
  NDivider,
  NSpace,
  NCheckbox,
  NDataTable,
  NModal,
  NText,
  FormInst
} from 'naive-ui'
import {
  ArrowBackOutline,
  SaveOutline,
  ImageOutline,
  PersonAddOutline,
  TrashOutline,
  CreateOutline
} from '@vicons/ionicons5'
import { useProjectStore } from '../../stores/projectStore'
import type { Project, Resolution, Collaborator } from '../../types/project'

const route = useRoute()
const router = useRouter()
const message = useMessage()
const projectStore = useProjectStore()

// 表单引用
const formRef = ref<FormInst | null>(null)
const collaboratorFormRef = ref<FormInst | null>(null)

// 获取项目ID
const projectId = computed(() => route.params.id as string)

// 分辨率选择
const selectedResolution = ref('720p')

// 协作者对话框
const showAddCollaboratorModal = ref(false)
const collaboratorForm = reactive({
  username: '',
  role: 'viewer'
})

// 项目表单数据
const projectForm = reactive<Partial<Project> & {
  autoSave: boolean;
  autoSaveInterval: number;
  versionControl: boolean;
  physicsEnabled: boolean;
  exportSettings: {
    includeAudio: boolean;
    includeMetadata: boolean;
    optimizeForWeb: boolean;
    defaultFormat: string;
  }
}>({
  id: '',
  name: '',
  description: '',
  ownerId: '',
  collaborators: [],
  tags: [],
  visibility: 'private',
  thumbnail: '',
  resolution: { width: 1280, height: 720, aspectRatio: '16:9' },
  frameRate: 30,
  autoSave: true,
  autoSaveInterval: 5,
  versionControl: true,
  physicsEnabled: false,
  exportSettings: {
    includeAudio: true,
    includeMetadata: true,
    optimizeForWeb: true,
    defaultFormat: 'mp4'
  }
})

// 表单验证规则
const formRules = {
  name: {
    required: true,
    message: '请输入项目名称',
    trigger: 'blur'
  }
}

// 协作者表单验证规则
const collaboratorRules = {
  username: {
    required: true,
    message: '请输入用户名或邮箱',
    trigger: 'blur'
  },
  role: {
    required: true,
    message: '请选择角色',
    trigger: 'blur'
  }
}

// 可见性选项
const visibilityOptions = [
  { label: '私有', value: 'private' },
  { label: '公开', value: 'public' },
  { label: '未列出', value: 'unlisted' }
]

// 分辨率选项
const resolutionOptions = [
  { label: '720p (1280x720)', value: '720p' },
  { label: '1080p (1920x1080)', value: '1080p' },
  { label: '4K (3840x2160)', value: '4k' },
  { label: '方形 (1080x1080)', value: 'square' },
  { label: '竖屏 (1080x1920)', value: 'portrait' },
  { label: '自定义', value: 'custom' }
]

// 帧率选项
const frameRateOptions = [
  { label: '24 FPS (电影)', value: 24 },
  { label: '30 FPS (标准)', value: 30 },
  { label: '60 FPS (高帧率)', value: 60 }
]

// 导出格式选项
const exportFormatOptions = [
  { label: 'MP4', value: 'mp4' },
  { label: 'WebM', value: 'webm' },
  { label: 'GIF', value: 'gif' },
  { label: 'PNG 序列', value: 'png-sequence' }
]

// 协作者角色选项
const roleOptions = [
  { label: '查看者', value: 'viewer' },
  { label: '编辑者', value: 'editor' },
  { label: '管理员', value: 'admin' }
]

// 协作者表格列
const collaboratorColumns = computed<DataTableColumns<Collaborator>>(() => [
  {
    title: '用户名',
    key: 'userId',
    render(row) {
      // 实际项目中应该根据 userId 获取用户名
      return h('div', {}, row.userId)
    }
  },
  {
    title: '角色',
    key: 'role',
    render(row) {
      const roleMap: Record<string, string> = {
        viewer: '查看者',
        editor: '编辑者',
        admin: '管理员'
      }
      return h('div', {}, roleMap[row.role] || row.role)
    }
  },
  {
    title: '加入时间',
    key: 'joinedAt',
    render(row) {
      const date = new Date(row.joinedAt)
      return h('div', {}, date.toLocaleDateString())
    }
  },
  {
    title: '状态',
    key: 'status',
    render(row) {
      const statusMap: Record<string, { text: string, type: 'success' | 'warning' | 'error' | 'info' }> = {
        active: { text: '已加入', type: 'success' },
        pending: { text: '待确认', type: 'warning' },
        rejected: { text: '已拒绝', type: 'error' }
      }
      const status = statusMap[row.status] || { text: row.status, type: 'info' }
      return h('n-tag', { type: status.type, size: 'small' }, { default: () => status.text })
    }
  },
  {
    title: '操作',
    key: 'actions',
    render(row) {
      return h('div', { style: 'display: flex; gap: 8px;' }, [
        h(
          NButton,
          {
            size: 'small',
            quaternary: true,
            onClick: () => editCollaborator(row)
          },
          { icon: () => h(NIcon, null, { default: () => h(CreateOutline) }) }
        ),
        h(
          NButton,
          {
            size: 'small',
            quaternary: true,
            onClick: () => removeCollaborator(row)
          },
          { icon: () => h(NIcon, null, { default: () => h(TrashOutline) }) }
        )
      ])
    }
  }
])

// 监听分辨率选择变化
const updateResolution = () => {
  switch (selectedResolution.value) {
    case '720p':
      projectForm.resolution = { width: 1280, height: 720, aspectRatio: '16:9' }
      break
    case '1080p':
      projectForm.resolution = { width: 1920, height: 1080, aspectRatio: '16:9' }
      break
    case '4k':
      projectForm.resolution = { width: 3840, height: 2160, aspectRatio: '16:9' }
      break
    case 'square':
      projectForm.resolution = { width: 1080, height: 1080, aspectRatio: '1:1' }
      break
    case 'portrait':
      projectForm.resolution = { width: 1080, height: 1920, aspectRatio: '9:16' }
      break
    // custom 保持当前值不变
  }
}

// 加载项目数据
const loadProject = async () => {
  try {
    const result = await projectStore.fetchProject(projectId.value)
    if (result) {
      // 复制基本属性
      Object.assign(projectForm, result)
      
      // 设置分辨率选择
      if (result.resolution) {
        const { width, height } = result.resolution
        if (width === 1280 && height === 720) {
          selectedResolution.value = '720p'
        } else if (width === 1920 && height === 1080) {
          selectedResolution.value = '1080p'
        } else if (width === 3840 && height === 2160) {
          selectedResolution.value = '4k'
        } else if (width === 1080 && height === 1080) {
          selectedResolution.value = 'square'
        } else if (width === 1080 && height === 1920) {
          selectedResolution.value = 'portrait'
        } else {
          selectedResolution.value = 'custom'
        }
      }
      
      // 设置默认值（实际项目中这些可能来自项目属性）
      projectForm.autoSave = result.autoSave !== undefined ? result.autoSave : true
      projectForm.autoSaveInterval = result.autoSaveInterval || 5
      projectForm.versionControl = result.versionControl !== undefined ? result.versionControl : true
      projectForm.physicsEnabled = result.physicsEnabled !== undefined ? result.physicsEnabled : false
      
      // 导出设置
      projectForm.exportSettings = {
        includeAudio: true,
        includeMetadata: true,
        optimizeForWeb: true,
        defaultFormat: 'mp4',
        ...(result.exportSettings || {})
      }
    } else {
      message.error('加载项目数据失败')
    }
  } catch (error) {
    console.error('加载项目数据错误:', error)
    message.error('加载项目数据时发生错误')
  }
}

// 保存项目设置
const saveSettings = async () => {
  try {
    await formRef.value?.validate()
    
    // 更新项目数据
    const result = await projectStore.updateProject({
      id: projectId.value,
      ...projectForm
    })
    
    if (result) {
      message.success('保存成功')
    } else {
      message.error('保存失败')
    }
  } catch (error) {
    console.error('保存项目设置错误:', error)
    message.error('表单验证失败或保存时发生错误')
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 添加协作者
const addCollaborator = async () => {
  try {
    await collaboratorFormRef.value?.validate()
    
    // 创建新协作者
    const newCollaborator: Collaborator = {
      userId: collaboratorForm.username, // 实际项目中应该通过用户名查找用户ID
      role: collaboratorForm.role,
      joinedAt: new Date().toISOString(),
      invitedBy: 'currentUserId', // 实际项目中应该使用当前用户ID
      status: 'pending',
      permissions: []
    }
    
    // 根据角色设置权限
    switch (collaboratorForm.role) {
      case 'viewer':
        newCollaborator.permissions = ['view']
        break
      case 'editor':
        newCollaborator.permissions = ['view', 'edit']
        break
      case 'admin':
        newCollaborator.permissions = ['view', 'edit', 'manage']
        break
    }
    
    // 添加到协作者列表
    projectForm.collaborators = projectForm.collaborators || []
    projectForm.collaborators.push(newCollaborator)
    
    // 重置表单
    collaboratorForm.username = ''
    collaboratorForm.role = 'viewer'
    
    message.success('已添加协作者，等待对方确认')
    showAddCollaboratorModal.value = false
  } catch (error) {
    console.error('添加协作者错误:', error)
  }
}

// 取消添加协作者
const cancelAddCollaborator = () => {
  collaboratorForm.username = ''
  collaboratorForm.role = 'viewer'
  showAddCollaboratorModal.value = false
}

// 编辑协作者
const editCollaborator = (collaborator: Collaborator) => {
  message.info('编辑协作者功能开发中')
  // 实际项目中应该打开编辑对话框
}

// 移除协作者
const removeCollaborator = (collaborator: Collaborator) => {
  if (!projectForm.collaborators) return
  
  const index = projectForm.collaborators.findIndex(c => c.userId === collaborator.userId)
  if (index !== -1) {
    projectForm.collaborators.splice(index, 1)
    message.success('已移除协作者')
  }
}

// 上传缩略图前处理
const beforeUploadThumbnail = (data: any) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    projectForm.thumbnail = e.target?.result as string
  }
  reader.readAsDataURL(data.file.file)
  return false // 阻止默认上传行为
}

// 监听分辨率选择变化
watch(selectedResolution, updateResolution)

// 初始化
onMounted(() => {
  loadProject()
})
</script>

<style lang="scss" scoped>
.project-settings-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .settings-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: 500;
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .collaborators-section {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      h3 {
        margin: 0;
      }
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .project-settings-container {
    padding: 10px;
  }
}
</style> 